package com.blockmeta.bbs.baselibrary.utils;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.blockmeta.bbs.baselibrary.base.app.BaseApp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageTools
{
	public static String app_file_dir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "blockmeta";
	public static final int Image_Max_Size=1024;

	public static Bitmap getImageFromUri(Uri uri, int maxSize)
	{
		BitmapFactory.Options o = null;
		InputStream stream = null;
		try
		{
			// Common.d("uri path: " + uri.getPath());
			o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			stream = BaseApp.getApp().getContentResolver().openInputStream(uri);
			BitmapFactory.decodeStream(stream, null, o);
			stream.close();

			int heightRatio = (int) Math.ceil((float) o.outHeight / (float) maxSize);
			int widthRatio = (int) Math.ceil((float) o.outWidth / (float) maxSize);
			int scale = 1;
			if ((heightRatio > 1) && (widthRatio > 1))
			{
				if (heightRatio > widthRatio)
				{
					scale = heightRatio;
				}
				else
				{
					scale = widthRatio;
				}
			}
			// Common.d("Before resize: " + o.outWidth + ":" + o.outHeight);
			// Common.d("Scale: " + scale);
			o = new BitmapFactory.Options();
			o.inSampleSize = scale;
			o.inDither = false;
			stream = BaseApp.getApp().getContentResolver().openInputStream(uri);
			Bitmap bScale = BitmapFactory.decodeStream(stream, null, o);
			stream.close();

			int longSide = bScale.getWidth() > bScale.getHeight() ? bScale.getWidth() : bScale.getHeight();
			float ratio = (float) longSide / (float) maxSize;

			Bitmap bResize = null;
			if (longSide > maxSize)
			{
				bResize = Bitmap.createScaledBitmap(bScale, (int) (bScale.getWidth() / ratio), (int) (bScale.getHeight() / ratio), true);
			}
			else
			{
				bResize = Bitmap.createBitmap(bScale);
			}

			int degrees = 0;
			String realPath = getPath(BaseApp.getApp(), uri);
			if (realPath != null)
			{
				ExifInterface exif = new ExifInterface(realPath);
				int orientation1 = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
				if (orientation1 != 0)
				{
					switch (orientation1)
					{
					case ExifInterface.ORIENTATION_ROTATE_270:
						degrees = 270;
					case ExifInterface.ORIENTATION_ROTATE_180:
						degrees = 180;
					case ExifInterface.ORIENTATION_ROTATE_90:
						degrees = 90;
					}
				}
			}

			int orientation2 = getOrientation(uri);
			if (orientation2 != 0)
			{
				degrees = orientation2;
			}
			// Common.d("degree : " + degrees);

			o = new BitmapFactory.Options();
			o.inPurgeable = true;
			o.inInputShareable = true;
			Matrix mtx = new Matrix();
			mtx.postRotate(degrees);
			Bitmap bRotate = Bitmap.createBitmap(bResize, 0, 0, bResize.getWidth(), bResize.getHeight(), mtx, true);
			// Common.d("After resize: " + bRotate.getWidth() + ":" +
			// bRotate.getHeight());
			return bRotate;
		}
		catch (Exception e)
		{
		}
		finally
		{
		}
		return null;
	}

	public static Uri saveToFile(Bitmap bitmap, File dir, String fileName, int quality)
	{
		try
		{
			int tSize = Image_Max_Size;
			tSize = tSize == 0 ? (int) BaseApp.getApp().getScreenWidhPixel() : tSize;
			int tWidth = bitmap.getWidth();
			int tHeight = bitmap.getHeight();

			if (tWidth > tSize || tHeight > tSize)
			{
				float tScaleWidth = tWidth * 1.f / tSize;
				float tScaleHeight = tHeight * 1.f / tSize;
				float tScale = tScaleWidth > tScaleHeight ? tScaleWidth : tScaleHeight;
				tScale = tScale >= 1 ? tScale : 1;

				bitmap = Bitmap.createScaledBitmap(bitmap, (int) (tWidth / tScale), (int) (tHeight / tScale), false);
			}

			if (!dir.exists())
			{
				dir.mkdirs();
			}
			File targetFile = new File(dir, fileName + ".jpg");
			FileOutputStream out = new FileOutputStream(targetFile);
			bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
			out.flush();
			out.close();
			return Uri.fromFile(targetFile);
		}
		catch (Exception e)
		{
			return null;
		}
	}

	public static void saveBitmap(Bitmap bitmap, File path)
	{
		FileOutputStream out = null;
		try
		{
			out = new FileOutputStream(path);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
			out.flush();
			out.close();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}


	public static int getOrientation(Uri uri)
	{
		try
		{
			Cursor cursor = BaseApp.getApp().getContentResolver().query(uri, new String[]
			{ MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
			if (cursor.moveToFirst())
			{
				int result = cursor.getInt(0);
				cursor.close();
				return result;
			}
			else
			{
				return 0;
			}
		}
		catch (Exception e)
		{
			return 0;
		}
	}

	public static Bitmap getBitmap(int res, int size)
	{
		Bitmap BitmapOrg = BitmapFactory.decodeResource(BaseApp.getApp().getResources(), res);
		int width = BitmapOrg.getWidth();
		int height = BitmapOrg.getHeight();

		int longSide = width > height ? width : height;
		float ratio = (float) longSide / (float) size;
		Bitmap bResize = null;
		if (longSide > size)
		{
			bResize = Bitmap.createScaledBitmap(BitmapOrg, (int) (BitmapOrg.getWidth() / ratio), (int) (BitmapOrg.getHeight() / ratio), true);
		}
		else
		{
			bResize = Bitmap.createBitmap(BitmapOrg);
		}
		return bResize;
	}

	public static Drawable getDrawable(int res, int size)
	{
		Bitmap bitmapOrg = BitmapFactory.decodeResource(BaseApp.getApp().getResources(), res);
		int width = bitmapOrg.getWidth();
		int height = bitmapOrg.getHeight();

		int longSide = width > height ? width : height;
		float ratio = (float) longSide / (float) size;
		Bitmap bResize = null;
		if (longSide > size)
		{
			bResize = Bitmap.createScaledBitmap(bitmapOrg, (int) (bitmapOrg.getWidth() / ratio), (int) (bitmapOrg.getHeight() / ratio), true);
		}
		else
		{
			bResize = Bitmap.createBitmap(bitmapOrg);
		}
		return new BitmapDrawable(bResize);
	}

	public static Drawable getDrawableWithBounds(int res, int size)
	{
		Drawable drawableOrg = BaseApp.getApp().getResources().getDrawable(res);
		int width = drawableOrg.getIntrinsicWidth();
		int height = drawableOrg.getIntrinsicHeight();

		int longSide = width > height ? width : height;
		float ratio = (float) longSide / (float) size;
		drawableOrg.setBounds(0, 0, (int) (width / ratio), (int) (height / ratio));
		// Common.i("getDrawableWithBounds: " + drawableOrg.getBounds().width()
		// + ":" + drawableOrg.getBounds().height());
		return drawableOrg;
	}

	public static Bitmap rotateLeft(Bitmap bitmap)
	{
		Matrix mtx = new Matrix();
		mtx.postRotate(-90);
		Bitmap bRotate = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);
		return bRotate;
	}

	public static Bitmap rotateRight(Bitmap bitmap)
	{
		Matrix mtx = new Matrix();
		mtx.postRotate(90);
		Bitmap bRotate = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);
		return bRotate;
	}

	public static Bitmap getImageFromUriFitWidth(Uri pUri, int pWidth)
	{
		BitmapFactory.Options o = null;
		InputStream stream = null;
		try
		{
			o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			stream = BaseApp.getApp().getContentResolver().openInputStream(pUri);
			BitmapFactory.decodeStream(stream, null, o);
			stream.close();

			int widthRatio = (int) Math.ceil((float) o.outWidth / (float) pWidth);
			int scale = 1;
			if ((widthRatio > 1))
			{
				scale = widthRatio;
			}

			o = new BitmapFactory.Options();
			o.inSampleSize = scale;
			o.inDither = false;
			stream = BaseApp.getApp().getContentResolver().openInputStream(pUri);
			Bitmap bScale = BitmapFactory.decodeStream(stream, null, o);
			stream.close();

			int degrees = 0;
			String realPath = getPath(BaseApp.getApp(), pUri);
			if (realPath != null)
			{
				ExifInterface exif = new ExifInterface(realPath);
				int orientation1 = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
				if (orientation1 != 0)
				{
					switch (orientation1)
					{
					case ExifInterface.ORIENTATION_ROTATE_270:
						degrees = 270;
					case ExifInterface.ORIENTATION_ROTATE_180:
						degrees = 180;
					case ExifInterface.ORIENTATION_ROTATE_90:
						degrees = 90;
					}
				}
			}

			int orientation2 = getOrientation(pUri);
			if (orientation2 != 0)
			{
				degrees = orientation2;
			}

			o = new BitmapFactory.Options();
			o.inPurgeable = true;
			o.inInputShareable = true;
			Matrix mtx = new Matrix();
			mtx.postRotate(degrees);
			Bitmap bRotate = Bitmap.createBitmap(bScale, 0, 0, bScale.getWidth(), bScale.getHeight(), mtx, true);
			return bRotate;
		}
		catch (Exception e)
		{
		}
		catch (OutOfMemoryError e)
		{

		}
		finally
		{
		}
		return null;
	}

	public static String getPath(final Context context, final Uri uri)
	{
		// DocumentProvider
		if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.KITKAT
				&& DocumentsContract.isDocumentUri(context, uri)) {

			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}

				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] {
						split[1]
				};

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {
			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 *
	 * @param context The context.
	 * @param uri The Uri to query.
	 * @param selection (Optional) Filter used in the query.
	 * @param selectionArgs (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	public static String getDataColumn(Context context, Uri uri, String selection,
									   String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = {
				column
		};

		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
					null);
			if (cursor != null && cursor.moveToFirst()) {
				final int column_index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(column_index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}


	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}


	public static int byteSizeOf(Bitmap bitmap) {

		if(bitmap==null){
			return 0;
		}

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			return bitmap.getAllocationByteCount();
		} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
			return bitmap.getByteCount();
		} else {
			return bitmap.getRowBytes() * bitmap.getHeight();
		}
	}

	private static int getReroteDegree(String realPath, Uri uri) throws IOException
	{
		int degrees = 0;
		if (realPath != null)
		{
			ExifInterface exif = new ExifInterface(realPath);
			int orientation1 = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			if (orientation1 != 0)
			{
				switch (orientation1)
				{
					case ExifInterface.ORIENTATION_ROTATE_270:
						degrees = 270;
						break;
					case ExifInterface.ORIENTATION_ROTATE_180:
						degrees = 180;
						break;
					case ExifInterface.ORIENTATION_ROTATE_90:
						degrees = 90;
						break;
				}
			}
		}
		else
		{
			int orientation2 = getOrientation(uri);
			if (orientation2 != 0)
			{
				degrees = orientation2;
			}
		}
		return degrees;
	}

	public static int[] getFileSize(String imagePath)
	{
		int[] res = new int[2];

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		options.inSampleSize = 1;
		BitmapFactory.decodeFile(imagePath, options);

		res[0] = options.outWidth;
		res[1] = options.outHeight;

		return res;
	}

	public static File compressFile(String srcFile, String dstFile, int quality, int width, int height, Bitmap.CompressFormat format)
	{
		int[] fileSize = getFileSize(srcFile);
		int actualWidth = fileSize[0];
		int actualHeight = fileSize[1];

		if (actualHeight < 0 || actualWidth < 0)
		{
			Bitmap tBitmap = BitmapFactory.decodeFile(srcFile);
			actualHeight = tBitmap.getHeight();
			actualWidth = tBitmap.getWidth();
		}
		if(actualHeight == 0 || actualWidth == 0){
			actualHeight = 500;
			actualWidth = 500;
		}

//		float imgRatio = actualWidth * 1.0f / actualHeight * 1.0f;
//		width = width == 0 ? actualWidth * 1 / 2 : width;
//		height = height == 0 ? actualHeight * 1 / 2 : height;
//
//		if (actualHeight > height || actualWidth > width) {
//			if (imgRatio < imgRatio) {
//				imgRatio = height / actualHeight;
//				actualWidth = (int) (imgRatio * actualWidth);
//				actualHeight = (int) height;
//			} else if (imgRatio > height) {
//				imgRatio = width / actualWidth;
//				actualHeight = (int) (imgRatio * actualHeight);
//				actualWidth = (int) width;
//			} else {
//				actualHeight = (int) height;
//				actualWidth = (int) width;
//			}
//		}

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = false;
		options.inSampleSize = 1;//calculateInSampleSize(options, actualWidth, actualHeight);
//		options.inPurgeable = true;
//		options.inInputShareable = true;
//		options.inTempStorage = new byte[16 * 1024];

		Bitmap bmp = null;
		Bitmap scaledBitmap = null;
		try {
			//load the bitmap from its path
			bmp = BitmapFactory.decodeFile(srcFile, options);
			if (bmp == null) {

				InputStream inputStream = null;
				try {
					inputStream = new FileInputStream(srcFile);
					BitmapFactory.decodeStream(inputStream, null, options);
					inputStream.close();
				} catch (FileNotFoundException exception) {
					exception.printStackTrace();
				} catch (IOException exception) {
					exception.printStackTrace();
				}
			}
		} catch (OutOfMemoryError exception) {
			exception.printStackTrace();
		}

		try {
			scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
		} catch (OutOfMemoryError exception) {
			exception.printStackTrace();
		}

		float ratioX = actualWidth / (float) options.outWidth;
		float ratioY = actualHeight / (float) options.outHeight;

		Matrix scaleMatrix = new Matrix();
		scaleMatrix.setScale(ratioX, ratioY, 0, 0);

		Canvas canvas = new Canvas(scaledBitmap);
		canvas.setMatrix(scaleMatrix);
		canvas.drawBitmap(bmp, 0, 0, new Paint(Paint.FILTER_BITMAP_FLAG));

		//check the rotation of the image and display it properly


		try {
			Matrix matrix = new Matrix();

			FileOutputStream fos = new FileOutputStream(new File(dstFile));

			matrix.postRotate(getReroteDegree(srcFile, Uri.fromFile(new File(srcFile))));
			Bitmap.createBitmap(scaledBitmap, 0, 0,
					scaledBitmap.getWidth(), scaledBitmap.getHeight(),
					matrix, true).compress(format, quality, fos );
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new File(dstFile);
	}

	public static Uri saveToFile(Bitmap bitmap, File dir, String fileName, int quality, int tSize)
	{
		try
		{
			tSize = tSize == 0 ? (int) BaseApp.getApp().getScreenWidhPixel() : tSize;
			int tWidth = bitmap.getWidth();
			int tHeight = bitmap.getHeight();

			if (tWidth > tSize || tHeight > tSize)
			{
				float tScaleWidth = tWidth * 1.f / tSize;
				float tScaleHeight = tHeight * 1.f / tSize;
				float tScale = tScaleWidth > tScaleHeight ? tScaleWidth : tScaleHeight;
				tScale = tScale >= 1 ? tScale : 1;

				bitmap = Bitmap.createScaledBitmap(bitmap, (int) (tWidth / tScale), (int) (tHeight / tScale), false);
			}

			if (!dir.exists())
			{
				dir.mkdirs();
			}
			File targetFile = new File(dir, fileName + ".jpg");
			FileOutputStream out = new FileOutputStream(targetFile);
			bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
			out.flush();
			out.close();
			return Uri.fromFile(targetFile);
		}
		catch (Exception e)
		{
			return null;
		}
	}

	public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
	{
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth)
		{
			final int heightRatio = Math.round((float) height / (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}

}
